package org.ihelpuoo.db;

import java.sql.Array;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.NClob;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Savepoint;
import java.sql.Statement;
import java.sql.Struct;
import java.util.Map;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.ihelpuoo.db.sql.SQLUtils;
import org.ihelpuoo.lang.ObjectUtils;

/**
 * <b>ConnectProxy class:</b>
 * <hr color=grey size=1>
 *
 * A Proxy of Connection object. When Database restarted, the proxy will reconnect
 * with the DB when process query/update etc. If re-connection failed, SQLException
 * will be rised.
 * <br><br>
 * Of cause, commit() and rollback will not make sense for catching the Exception.
 *
 * @author zozoh  created @ 2006
 *
 */
public class PoolConnectionProxy implements ConnectionProxy
{

	private Logger			log	= Logger.getLogger(PoolConnectionProxy.class);

	private Connection		conn;
	private Statement		statement;
	private ResultSet		rs;
	private ConnectionPool	pool;
	private boolean			isClosed;
	private boolean			isAutoCommit;

	private PoolConnectionProxy()
	{
		this.isClosed = true;
		this.isAutoCommit = true;
	}

	public PoolConnectionProxy(ConnectionPool pool)
	{
		this();
		this.pool = pool;
		buildConnection();
	}

	private void buildConnection()
	{
		try
		{
			conn = DriverManager.getConnection(pool.url,pool.userName,pool.password);
			if (conn.getAutoCommit() != this.isAutoCommit)
				conn.setAutoCommit(this.isAutoCommit);
		}
		catch (Exception e)
		{
			log.warn(e.getMessage());
			conn = null;
		}
	}

	private void checkConnectionIsNull() throws SQLException
	{
		if (null == conn)
			throwConnectionIsNullException();
	}

	private void throwConnectionIsNullException() throws SQLException
	{
		throw new SQLException("Connection is NULL!");
	}

	private void resetConnection2Null()
	{
		try
		{
			if (null != conn)
				conn.close();
		}
		catch (Exception e)
		{
		}
		conn = null;
	}

	protected void depose()
	{
		if (null == conn)
			return;
		clearResult();
		resetConnection2Null();
	}

	private void clearResult()
	{
		if (null != rs)
		{
			try
			{
				rs.close();
			}
			catch (SQLException e)
			{
			}
		}
		if (null != statement)
		{
			try
			{
				statement.close();
			}
			catch (SQLException e)
			{
			}
		}
		rs = null;
		statement = null;
	}

	/**
	 * @return true: has a valid connection, false: connection is null;
	 */
	protected void checkState() throws SQLException
	{
		if (isClosed)
			throw new ConnectionIsClosedException();
		if (null == conn)
		{
			buildConnection();
			checkConnectionIsNull();
		}
	}

	public ResultSetProxy queryForward(String sql) throws SQLException
	{
		return query(sql,ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_READ_ONLY);
	}

	public ResultSetProxy query(String sql) throws SQLException
	{
		return query(sql,ResultSet.TYPE_SCROLL_INSENSITIVE);
	}

	public ResultSetProxy query(String sql, int scrollType) throws SQLException
	{
		return query(sql,scrollType,ResultSet.CONCUR_READ_ONLY);
	}

	public ResultSetProxy query(String sql, int scrollType, int cursorType) throws SQLException
	{
		try
		{
			statement = conn.createStatement(scrollType,cursorType);
			rs = statement.executeQuery(sql);
			return new ResultSetProxy(rs,this);
		}
		catch (Exception e)
		{
			resetConnection2Null();
			throw SQLUtils.wrapSQLException(e);
		}
	}

	public boolean execute(String sql) throws SQLException
	{
		try
		{
			statement = conn
					.createStatement(ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_UPDATABLE);
			return statement.execute(sql);
		}
		catch (Exception e)
		{
			resetConnection2Null();
			throw SQLUtils.wrapSQLException(e);
		}
	}

	public int executeUpdate(String sql) throws SQLException
	{
		try
		{
			statement = conn
					.createStatement(ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_UPDATABLE);
			return statement.executeUpdate(sql);
		}
		catch (Exception e)
		{
			resetConnection2Null();
			throw SQLUtils.wrapSQLException(e);
		}
	}

	public ResultSet modify(String tableName) throws SQLException
	{
		try
		{
			statement = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_UPDATABLE);
			return statement.executeQuery("SELECT * FROM " + tableName);
		}
		catch (Exception e)
		{
			resetConnection2Null();
			throw SQLUtils.wrapSQLException(e);
		}
	}

	public ResultSetMetaData meta(String tableName) throws SQLException
	{
		try
		{
			statement = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_UPDATABLE);
			return statement.executeQuery("SELECT * FROM " + tableName).getMetaData();
		}
		catch (Exception e)
		{
			resetConnection2Null();
			throw SQLUtils.wrapSQLException(e);
		}
	}

	protected void setClosed(boolean isClosed)
	{
		this.isClosed = isClosed;
	}

	public Connection connection()
	{
		return this.conn;
	}

	/*
	 * =======================================================
	 */
	/**
	 * @see java.sql.Connection.getAutoCommit()
	 * 
	 * @return true: auto-commit mode. false:
	 * @throws SQLException if a database access error occurs
	 */
	public boolean getAutoCommit() throws SQLException
	{
		checkConnectionIsNull();
		try
		{
			return conn.getAutoCommit();
		}
		catch (Exception e)
		{
			resetConnection2Null();
			throw SQLUtils.wrapSQLException(e);
		}
	}

	public void commit() throws SQLException
	{
		checkConnectionIsNull();
		try
		{
			conn.commit();
		}
		catch (Exception e)
		{
			resetConnection2Null();
			throw SQLUtils.wrapSQLException(e);
		}
	}

	public boolean isClosed()
	{
		return isClosed;
	}

	public void close()
	{
		try
		{
			if (null != conn)
			{
				clearResult();
				setAutoCommit(true);
			}
		}
		catch (Exception e)
		{
			resetConnection2Null();
		}
		finally
		{
			pool.close(this);
		}
	}

	/**
	 * @see java.sql.Connection.setAutoCommit()
	 * 
	 * @param autoCommit <code>true</code> to enable auto-commit mode; 
	 *         <code>false</code> to disable it
	 * @throws SQLException if a database access error occurs
	 */
	public void setAutoCommit(boolean autoCommit) throws SQLException
	{
		checkConnectionIsNull();
		this.isAutoCommit = autoCommit;
		if (null == conn)
			return;
		try
		{
			if (conn.getAutoCommit() == this.isAutoCommit)
				return;
			conn.setAutoCommit(this.isAutoCommit);
		}
		catch (Exception e)
		{
			resetConnection2Null();
			throw SQLUtils.wrapSQLException(e);
		}
	}

	public void rollback() throws SQLException
	{
		checkConnectionIsNull();
		try
		{
			if (null != conn)
				conn.rollback();
		}
		catch (Exception e)
		{
			resetConnection2Null();
			throw SQLUtils.wrapSQLException(e);
		}
	}

	public void clearWarnings() throws SQLException
	{
		checkConnectionIsNull();
		try
		{
			if (null != conn)
				conn.clearWarnings();
		}
		catch (Exception e)
		{
			resetConnection2Null();
			throw SQLUtils.wrapSQLException(e);
		}
	}

	public Statement createStatement() throws SQLException
	{
		checkConnectionIsNull();
		try
		{
			return conn.createStatement();
		}
		catch (Exception e)
		{
			resetConnection2Null();
			throw SQLUtils.wrapSQLException(e);
		}
	}

	public Statement createStatement(int resultSetType, int resultSetConcurrency,
			int resultSetHoldability) throws SQLException
	{
		checkConnectionIsNull();
		try
		{
			return conn.createStatement(resultSetType,resultSetConcurrency,resultSetHoldability);
		}
		catch (Exception e)
		{
			resetConnection2Null();
			throw SQLUtils.wrapSQLException(e);
		}
	}

	public Statement createStatement(int resultSetType, int resultSetConcurrency)
			throws SQLException
	{
		checkConnectionIsNull();
		try
		{
			return conn.createStatement(resultSetType,resultSetConcurrency);
		}
		catch (Exception e)
		{
			resetConnection2Null();
			throw SQLUtils.wrapSQLException(e);
		}
	}

	public String getCatalog() throws SQLException
	{
		checkConnectionIsNull();
		try
		{
			return conn.getCatalog();
		}
		catch (Exception e)
		{
			resetConnection2Null();
			throw SQLUtils.wrapSQLException(e);
		}
	}

	public int getHoldability() throws SQLException
	{
		checkConnectionIsNull();
		try
		{
			return conn.getHoldability();
		}
		catch (Exception e)
		{
			resetConnection2Null();
			throw SQLUtils.wrapSQLException(e);
		}
	}

	public DatabaseMetaData getMetaData() throws SQLException
	{
		checkConnectionIsNull();
		try
		{
			return conn.getMetaData();
		}
		catch (Exception e)
		{
			resetConnection2Null();
			throw SQLUtils.wrapSQLException(e);
		}
	}

	public int getTransactionIsolation() throws SQLException
	{
		checkConnectionIsNull();
		try
		{
			return conn.getTransactionIsolation();
		}
		catch (Exception e)
		{
			resetConnection2Null();
			throw SQLUtils.wrapSQLException(e);
		}
	}

	public Map<String, Class<?>> getTypeMap() throws SQLException
	{
		checkConnectionIsNull();
		try
		{
			return conn.getTypeMap();
		}
		catch (Exception e)
		{
			resetConnection2Null();
			throw SQLUtils.wrapSQLException(e);
		}
	}

	public SQLWarning getWarnings() throws SQLException
	{
		checkConnectionIsNull();
		try
		{
			return conn.getWarnings();
		}
		catch (Exception e)
		{
			resetConnection2Null();
			throw SQLUtils.wrapSQLException(e);
		}
	}

	public boolean isReadOnly() throws SQLException
	{
		checkConnectionIsNull();
		try
		{
			return conn.isReadOnly();
		}
		catch (Exception e)
		{
			resetConnection2Null();
			throw SQLUtils.wrapSQLException(e);
		}
	}

	public String nativeSQL(String sql) throws SQLException
	{
		checkConnectionIsNull();
		try
		{
			return conn.nativeSQL(sql);
		}
		catch (Exception e)
		{
			resetConnection2Null();
			throw SQLUtils.wrapSQLException(e);
		}
	}

	public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency,
			int resultSetHoldability) throws SQLException
	{
		checkConnectionIsNull();
		try
		{
			return conn.prepareCall(sql,resultSetType,resultSetConcurrency,resultSetHoldability);
		}
		catch (Exception e)
		{
			resetConnection2Null();
			throw SQLUtils.wrapSQLException(e);
		}
	}

	public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency)
			throws SQLException
	{
		checkConnectionIsNull();
		try
		{
			return conn.prepareCall(sql,resultSetType,resultSetConcurrency);
		}
		catch (Exception e)
		{
			resetConnection2Null();
			throw SQLUtils.wrapSQLException(e);
		}
	}

	public CallableStatement prepareCall(String sql) throws SQLException
	{
		checkConnectionIsNull();
		try
		{
			return conn.prepareCall(sql);
		}
		catch (Exception e)
		{
			resetConnection2Null();
			throw SQLUtils.wrapSQLException(e);
		}
	}

	public PreparedStatement prepareStatement(String sql, int resultSetType,
			int resultSetConcurrency, int resultSetHoldability) throws SQLException
	{
		checkConnectionIsNull();
		try
		{
			return conn.prepareStatement(sql,resultSetType,resultSetConcurrency,
					resultSetHoldability);
		}
		catch (Exception e)
		{
			resetConnection2Null();
			throw SQLUtils.wrapSQLException(e);
		}
	}

	public PreparedStatement prepareStatement(String sql, int resultSetType,
			int resultSetConcurrency) throws SQLException
	{
		checkConnectionIsNull();
		try
		{
			return conn.prepareStatement(sql,resultSetType,resultSetConcurrency);
		}
		catch (Exception e)
		{
			resetConnection2Null();
			throw SQLUtils.wrapSQLException(e);
		}
	}

	public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys)
			throws SQLException
	{
		checkConnectionIsNull();
		try
		{
			return conn.prepareStatement(sql,autoGeneratedKeys);
		}
		catch (Exception e)
		{
			resetConnection2Null();
			throw SQLUtils.wrapSQLException(e);
		}
	}

	public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException
	{
		checkConnectionIsNull();
		try
		{
			return conn.prepareStatement(sql,columnIndexes);
		}
		catch (Exception e)
		{
			resetConnection2Null();
			throw SQLUtils.wrapSQLException(e);
		}
	}

	public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException
	{
		checkConnectionIsNull();
		try
		{
			return conn.prepareStatement(sql,columnNames);
		}
		catch (Exception e)
		{
			resetConnection2Null();
			throw SQLUtils.wrapSQLException(e);
		}
	}

	public PreparedStatement prepareStatement(String sql) throws SQLException
	{
		checkConnectionIsNull();
		try
		{
			return conn.prepareStatement(sql);
		}
		catch (Exception e)
		{
			resetConnection2Null();
			throw SQLUtils.wrapSQLException(e);
		}
	}

	public void releaseSavepoint(Savepoint savepoint) throws SQLException
	{
		checkConnectionIsNull();
		try
		{
			if (null != conn)
				conn.releaseSavepoint(savepoint);
		}
		catch (Exception e)
		{
			throw SQLUtils.wrapSQLException(e);
		}
	}

	public void rollback(Savepoint savepoint) throws SQLException
	{
		checkConnectionIsNull();
		try
		{
			conn.rollback(savepoint);
		}
		catch (Exception e)
		{
			resetConnection2Null();
			throw SQLUtils.wrapSQLException(e);
		}
	}

	public void setCatalog(String catalog) throws SQLException
	{
		checkConnectionIsNull();
		try
		{
			conn.setCatalog(catalog);
		}
		catch (Exception e)
		{
			resetConnection2Null();
			throw SQLUtils.wrapSQLException(e);
		}
	}

	public void setHoldability(int holdability) throws SQLException
	{
		checkConnectionIsNull();
		try
		{
			conn.setHoldability(holdability);
		}
		catch (Exception e)
		{
			resetConnection2Null();
			throw SQLUtils.wrapSQLException(e);
		}
	}

	public void setReadOnly(boolean readOnly) throws SQLException
	{
		checkConnectionIsNull();
		try
		{
			conn.setReadOnly(readOnly);
		}
		catch (Exception e)
		{
			resetConnection2Null();
			throw SQLUtils.wrapSQLException(e);
		}
	}

	public Savepoint setSavepoint() throws SQLException
	{
		checkConnectionIsNull();
		try
		{
			return conn.setSavepoint();
		}
		catch (Exception e)
		{
			resetConnection2Null();
			throw SQLUtils.wrapSQLException(e);
		}
	}

	public Savepoint setSavepoint(String name) throws SQLException
	{
		checkConnectionIsNull();
		try
		{
			return conn.setSavepoint(name);
		}
		catch (Exception e)
		{
			resetConnection2Null();
			throw SQLUtils.wrapSQLException(e);
		}
	}

	public void setTransactionIsolation(int level) throws SQLException
	{
		checkConnectionIsNull();
		try
		{
			conn.setTransactionIsolation(level);
		}
		catch (Exception e)
		{
			resetConnection2Null();
			throw SQLUtils.wrapSQLException(e);
		}
	}

	public void setTypeMap(Map<String, Class<?>> map) throws SQLException
	{
		checkConnectionIsNull();
		try
		{
			conn.setTypeMap(map);
		}
		catch (Exception e)
		{
			resetConnection2Null();
			throw SQLUtils.wrapSQLException(e);
		}
	}

	@Override
	public Array createArrayOf(String typeName, Object[] elements) throws SQLException
	{
		return null;
	}

	@Override
	public Blob createBlob() throws SQLException
	{
		return null;
	}

	@Override
	public Clob createClob() throws SQLException
	{
		return null;
	}

	@Override
	public NClob createNClob() throws SQLException
	{
		return null;
	}

	@Override
	public SQLXML createSQLXML() throws SQLException
	{
		return null;
	}

	@Override
	public Struct createStruct(String typeName, Object[] attributes) throws SQLException
	{
		return null;
	}

	@Override
	public Properties getClientInfo() throws SQLException
	{
		return null;
	}

	@Override
	public String getClientInfo(String name) throws SQLException
	{
		return null;
	}

	@Override
	public boolean isValid(int timeout) throws SQLException
	{
		return false;
	}

	@Override
	public void setClientInfo(Properties properties) throws SQLClientInfoException
	{
	}

	@Override
	public void setClientInfo(String name, String value) throws SQLClientInfoException
	{
	}

	@Override
	public boolean isWrapperFor(Class<?> iface) throws SQLException
	{
		if (ObjectUtils.isChildOf(iface,Connection.class))
			return true;
		return false;
	}

	@Override
	public <T> T unwrap(Class<T> iface) throws SQLException
	{
		if (isWrapperFor(iface))
		{
			return (T)rs;
		}
		return null;
	}
}
